package pnu.ssm.sbchild;

import pnu.ssm.key.Key;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.util.Log;
import android.view.MotionEvent;
import android.view.Window;

public class SplashActivity extends Activity {

	public static final String TAG = "SplashActivity";

	private int _splashTime = 3000;
	private Thread splashThread;
	boolean hasParent;
	private SharedPreferences pref;
	private SharedPreferences.Editor editor;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.activity_splash);

		buildUI();
		startSplash();
	}

	private void buildUI() {
		splashThread = new SplashThread();
		pref = getSharedPreferences(Key.prefKey, MODE_PRIVATE);
		editor = pref.edit();
		hasParent = pref.getBoolean(Key.hasParent, false);
	}

	@Override
	protected void onResume() {
		super.onResume();
		isNetworkConnected();
	}

	private void startSplash() {
		splashThread.start();
	}

	@Override
	public boolean onTouchEvent(MotionEvent event) {
		if (event.getAction() == MotionEvent.ACTION_DOWN) {
			synchronized (splashThread) {
				splashThread.notifyAll();
			}
		}
		return true;
	}

	private class SplashThread extends Thread {
		@Override
		public void run() {
			try {
				synchronized (this) {
					wait(3000);
				}
			} catch (InterruptedException e) {
				Log.e(TAG, e.getMessage());
			} finally {
				finish();

				Intent intent = null;
				//intent = new Intent(SplashActivity.this, TestActivity.class);
				
				if (hasParent) {
					intent = new Intent(SplashActivity.this, MainActivity.class);
				} else {
					intent = new Intent(SplashActivity.this, PairingActivity.class);
				}
				
				startActivity(intent);
			}
		}
	}

	private boolean isNetworkConnected() {
		ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
		NetworkInfo ni = cm.getActiveNetworkInfo();
		if (ni == null) {
			showDialog();
			return false;
		} else
			return true;
	}
	private void showDialog(){
		String msg = "인터넷이 연결되어 있지 않아 서버 접속이 불가합니다. 인터넷을 연결한 후 접속해주세요";

		AlertDialog.Builder alt_bld = new AlertDialog.Builder(this);
		
		alt_bld.setMessage(msg)
		.setCancelable(false)
		.setPositiveButton("확인",new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int id) {
				finish();
			}});
		
		AlertDialog alert = alt_bld.create();
		alert.setTitle("Mom's Locker");
		alert.setIcon(R.drawable.ic_launcher);
		alert.show();
	}
}
